/*
* @Author: Administrator
* @Date:   2018-01-27 15:07:55
* @Last Modified by:   Administrator
* @Last Modified time: 2018-01-27 15:14:35
*/
const path =  require('path')
const axios =  require('axios')
const qs = require('qs')
const bodyParser =  require('body-parser')
const favicon = require('serve-favicon')
const session = require('express-session')

const apiMiddle = (app) => {
  // body parser
  app.use(bodyParser.json())
  app.use(bodyParser.urlencoded({ extended: false }))
  app.use(favicon(path.join(__dirname,'../../favicon.ico')))
  // session
  app.use(session({
    maxAge: 10 * 60 * 1000,
    name: 'tid',
    resave: false,
    saveUninitialized: false,
    secret: 'I will teach you'
  }))

  // api代理
  app.use('/api/v1/user', require('./user_api.js'))
  app.use('/api', function(req, res, next) {
    const baseUrl = ' https://cnodejs.org/api' + req.path
    const config = {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      method: req.method,
      url: baseUrl,
      data: qs.stringify(req.body),
      params: req.query,
    }
    if(req.query.needToken || req.body.needToken) {
      if(req.session.user && req.session.user.accessToken) {
        config.data.accesstoken = config.params.accesstoken = req.session.user.accessToken
      } else {
        res.send({
          success: false,
          error_msg: '你需要登录进行操作',
        })
        return
      }
    }
    axios(config).then(result => {
      res.send(result.data)
    }).catch((e) => {
      if (e.data) {
        res.send(e.data)
      } else {
        next(e)
      }
    })
  })
}

module.exports = apiMiddle
